import requests
import json
import time
from openpyxl import Workbook, load_workbook
import os


headers = {"X-User-Token":"756283292c03bd29dbf8a721f5ca26bc", "content-type":"application/json"}

class Save_to_excel(object):
    def __init__(self, filename, header):
        """
        :param filename: 表格文件名
        :param class_:  存储类型  如：orderlist, depth, orderlist_depth
        """
        super(Save_to_excel, self).__init__()
        self.filename = filename
        if not os.path.exists(filename):  # 判断这个文件是否已经存在，否则创建
            wb = Workbook()  # 创建文件对象
            ws = wb.active
            header_dict = {}
            for i, d in enumerate(header):
                ws[f"{chr(i+65)}1"] = d
                # 这个key在哪个列（A/B/C...）
                header_dict[d] = chr(65 + i)
            self.headers = header_dict
            wb.save(filename)  # 保存文件
        else:
            header_dict = {}
            for i, d in enumerate(header):
                # 这个key在哪个列（A/B/C...）
                header_dict[d] = chr(65 + i)
            self.headers = header_dict
        # 读取行数和列数
        wb = load_workbook(filename)
        wb.guess_types = True
        sheet = wb.active
        row = sheet.max_row
        self.row = row + 1
        wb.close()

    def insert_data(self, data_list):
        """
        :param data_list: 数据列表，里面嵌套字典，且key应该为header
        :return:
        """
        wb = load_workbook(self.filename)  # 加载已经存在的Excel文件
        wb.guess_types = True
        sheet = wb.active
        header = self.headers
        for data in data_list:
            for k in data:
                sheet[f'{header[k]}{self.row}'] = data[k]
            self.row += 1
        wb.save(self.filename)
        wb.close()

# 计数
def count_alert_history (dict_in_list):
    new_list = []
    index = 0
    for i in dict_in_list:
        i = str(i)
        new_list.append(i)
    # print(type(new_list[0]))
    new_list = list(set(new_list))
    for i in new_list:
        new_list[index] = eval(i)
        new_list[index]["count"] = dict_in_list.count(new_list[index])
        index += 1
    return new_list

# 统计一周内告警信息，参数alarm_grade是告警级别(int),时间周期可改
def one_week_alarminfo(alarm_grade, type, keshi, cycle):
    # alarm_grade:告警等级  填写数字[1-3]即可
    # 获取当前时间戳作为统计结束时间
    etime = int(time.time())   # 结束时间

    """7天告警信息统计"""
    if cycle == 7 or cycle == 14:
        stime = etime - cycle*24*3600  # 开始时间
        params = {"etime":etime, "limit":20000, "p":1, "nodepath":keshi, "priorities":alarm_grade, "stime":stime, "type":type}
        ret = requests.get("https://nightingale.smyoa.com/api/mon/event/his", headers=headers, params=params)
        print(ret)
    
    else:
        """1日内未恢复告警"""
        stime = etime - 1*24*3600  # 开始时间
        params = {"etime":etime, "limit":2000000000, "p":1, "nodepath":"SMY", "stime":stime}
        ret = requests.get("https://nightingale.smyoa.com/api/mon/event/cur", headers=headers, params=params)

    alert_history_list = json.loads(ret.text)['dat']['list']
    index = 0
    print(len(alert_history_list))
    for alert_history in alert_history_list:
        if cycle == 7:
            alert_history = {x: alert_history[x] for x in alert_history.keys() if x ==  "sname" or x == "node_path" or x == "endpoint" or x == "status"}
        else:
            alert_history = {x: alert_history[x] for x in alert_history.keys() if x ==  "sname" or x == "node_path" or x == "endpoint" or x == "etime" or x =="priorities" or x == "status"}
            times = time.localtime(alert_history_list[index]['etime'])
            t = time.strftime("%Y--%m--%d %H:%M:%S", times)
            alert_history['etime'] = str(t)

        alert_history['status'] = str(alert_history['status'])
        alert_history_list[index] = alert_history
        index += 1
    if type == "alert" and cycle != 1:
        alert_history_list = list(filter(lambda x:"已发送" in x["status"], alert_history_list))
    alert_history_list = count_alert_history(alert_history_list)
    s = Save_to_excel(r"p{}.xlsx".format(keshi), ["node_path","endpoint", "sname", "priorities", "etime", "count", "status"])
    s.insert_data(alert_history_list)

# 用户
def user_get():
    ret = requests.get("https://nightingale.smyoa.com/api/uic/user?limit=10000&p=1&query=", headers=headers)
    user_list = json.loads(ret.text)['dat']['list']
    user_dict = {}
    for user in user_list:
        user_dict[user['id']]=user['dispname']
    return user_dict

# 用户组
def user_group_get():
    ret = requests.get("https://nightingale.smyoa.com/api/uic/team?limit=100000&p=1&query=", headers=headers)
    user_group_list = json.loads(ret.text)['dat']['list']
    user_group_dict = {}
    for user_group in user_group_list:
        user_group_dict[user_group['id']] = user_group['name']
    return user_group_dict

# 节点
def node_get():
    ret = requests.get("https://nightingale.smyoa.com/api/hsp/tree?query=", headers=headers)
    # print(json.loads(ret.text)['dat'][18])
    node_list = json.loads(ret.text)['dat']
    node_dict = {}
    for node in node_list:
        node_dict[node['id']] = node['path']
    return node_dict

# 拉取告警策略
def all_strategy(w_excel=False):
    ret = requests.get("https://nightingale.smyoa.com/api/mon/stra/", headers=headers)
    alarm_strategy_list = json.loads(ret.text)['dat']
    # alarm_strategy_info = alarm_strategy_list
    index = 0
    # print(alarm_strategy_list[0])
    if w_excel:
        for alarm_strategy in alarm_strategy_list:
            # 把用户id转换为用户名字
            user_index = 0
            for i in alarm_strategy['notify_user']:
                if i:
                    i = user_dict[i]
                    alarm_strategy['notify_user'][user_index] = i
                user_index += 1
            # 把用户组id转换为用户名字
            user_group_index = 0
            for i in alarm_strategy['notify_group']:
                if i:
                    i = user_group_dict[i]
                    alarm_strategy['notify_group'][user_group_index] = i
                user_group_index += 1
            # 把节点id转换为节点
            alarm_strategy['nid'] = node_dict[alarm_strategy['nid']]
            # 转换告警周期的单位
            alarm_strategy['converge'][0] = int(alarm_strategy['converge'][0])/60
            

            alarm_strategy = {x: str(alarm_strategy[x]) for x in alarm_strategy.keys() if x == "name" or x == "converge" or x == "notify_user" or x == "notify_group" or x == "nid" or x == "priority"}
            alarm_strategy_list[index] = alarm_strategy
            index +=1
            
        s = Save_to_excel("alarm.xlsx", ["name", "converge", "notify_group", "notify_user", "nid", "priority"])
        s.insert_data(alarm_strategy_list)
    else:
        return alarm_strategy_list

# 批量修改告警策略
def c_strategy(depart):
    strategy_list = all_strategy()
    for strategy in strategy_list:
        # print(strategy)
        if depart in node_dict[strategy['nid']]:
            # if strategy['priority'] == 2:
            #     strategy['priority'] = 3

            if strategy['priority'] == 3:
                strategy['converge'][0] = 20*60
                strategy['converge'][1] = 1
            # elif strategy['priority'] == 1:
            #     strategy['converge'][0] = 60*60
            #     strategy['converge'][1] = 2
            #     if 15 not in strategy['notify_user']:
            #         strategy['notify_user'].append(15)
            #     if 29 not in strategy['notify_user']:
            #         strategy['notify_user'].append(29)

            # if 'CPU使用率大于90' in strategy['name']:
            #     strategy['name'] = 'CPU使用率大于95%告警'
            #     strategy['exprs'][0]['threshold'] = 95
            # elif '内存使用率大于90' in strategy['name']:
            #     strategy['name'] = '内存使用率大于95%告警'
            #     strategy['exprs'][0]['threshold'] = 95
            
            # if 23 in strategy['notify_user'] and 30 not in strategy['notify_user']:
            #     strategy['notify_user'].remove(23)
            #     strategy['notify_user'].append(30)
            # if 28 in strategy['notify_user'] and 30 not in strategy['notify_user']:
            #     strategy['notify_user'].remove(28)
            #     strategy['notify_user'].append(30)

            # if 23 in strategy['notify_user']:
            #     strategy['notify_user'].remove(23)
            # if 28 in strategy['notify_user']:
            #     strategy['notify_user'].remove(28)
            # if 130 in strategy['notify_user']: # 柯晓峰
            #     strategy['notify_user'].remove(130)
            # if 10 in strategy['notify_user']: 
            #     strategy['notify_user'].remove(10)
            # if 10 not in strategy['notify_user']: # 思雨姐
            #     strategy['notify_user'].append(10)
            
            # print(strategy)
            strategy = json.dumps(strategy)
            tt = requests.put("https://nightingale.smyoa.com/api/mon/stra", headers=headers, data=strategy)
            print(tt.text)


if __name__ == "__main__":
    user_dict = user_get()
    user_group_dict = user_group_get()
    node_dict = node_get()
    keshi_list = ["SMY.information technology.beisheng", "SMY.information technology.app_web", "SMY.information technology.basic",
                  "SMY.information technology.bigdata", "SMY.information technology.framework", "SMY.information technology.fund_deal",
                  "SMY.information technology.operation", "SMY.information technology.riskone", "SMY.information technology.risktwo",
                  "SMY.information technology.taichao"
    ]
    ##### 一天或一周 #####
    one_week_alarminfo(None, 'alert', "SMY", 1)
    ##### 一天或一周 #####

    #####  半月告警统计 #####
    # for i in keshi_list:
    #     print(i)
    #     one_week_alarminfo(None, 'alert', i, 14)
    #####  半月告警统计 #####

    ###### 拉取所有告警策略 ######
    # all_strategy(w_excel=True)
    ###### 拉取所有告警策略 ######

    ######  只修改运维科室和其他科室的告警策略 除去了dba的告警策略  ######
    # a = ['beisheng', 'bigdata', 'framework', 'fund_deal', 'riskone', 'risktwo', 'taichao', 'basic', 'app_web']
    # b = ['Firewall', 'Switch', 'bak', 'harbor', 'iaas', 'k8s', 'middleware', 'monitor', 'nat', 'nginx', 'other', 'security', 'storage', 'windows']
    # for i in a:
    #     c_strategy(i)
    # for i in b:
    #     c_strategy('operation.'+i)
    ######  只修改运维科室和其他科室的告警策略 除去了dba的告警策略  ######

